// var mongoose = require('mongoose');
const {
    ObjectId
} = require('mongodb')
const jwt = require('jsonwebtoken');
const jsonParse = require('../../lib/jsonParse')
const bcrypt = require('bcrypt')
const gravatar = require('gravatar');
const secret = require('../../config/keys')
// 获取头部token，转成用户名
const Header = require('../../lib/getHeader');
// schemas集合
const Users = require('../../schemas/users').Users;
const UserRelatRoles = require('../../schemas/users').UserRelatRoles;
const Tokens = require('../../schemas/users').Tokens;
const MenusLists = require('../../schemas/users').MenusLists;
const AuthLists = require('../../schemas/users').AuthLists;
const RoleLists = require('../../schemas/users').RoleLists;
const AppLists = require('../../schemas/users').AppLists;
const RoleRelatMenu = require('../../schemas/users').RoleRelatMenu;
const RoleRelatDataAuth = require('../../schemas/users').RoleRelatDataAuth;
const RoleRelatHandleAuth = require('../../schemas/users').RoleRelatHandleAuth;
const CarStation = require('../../schemas/stations').CarStations

module.exports = {
    test(req, res) {
        res.json({
            msg: 'test成功'
        })
    },

    /**
     * Post 
     * api/login
     * 登录接口
     *  */
    async login(req, res) {
        console.log(req.body.userName)
        Users.findOne({
            userName: req.body.userName
        }).then(user => {
            if (user) {
                bcrypt.compare(req.body.passWord, user.passWord).then(isMatch => {
                    if (isMatch) {
                        // jwt.sign("规则", '加密名称'， )
                        const rule = {
                            id: user.id,
                            name: user.userName
                        }
                        jwt.sign(rule, secret.secretOrKey, {
                            expiresIn: secret.expiresTime
                        }, (err, token) => {
                            if (err) throw err;
                            const newToken = new Tokens({
                                token: token,
                                expiresIn: secret.expiresTime,
                                userName: user.userName,
                                expiresDate: new Date(new Date().getTime() + (8 * 60 * 60 * 1000))
                            })
                            newToken.save().then(o => {
                                let data = {
                                    token: `Bearer ${token}`
                                }
                                jsonParse.sendResult(res, 200, data, '登录成功')
                            })
                        })
                    } else {
                        jsonParse.sendResult(res, -1002)
                    }
                })
            } else {
                jsonParse.sendResult(res, -1002)
            }
        })
    },
    /**
     * Post 
     * api/login
     * 免密登录接口
     *  */
    async autoLoginByToken(req, res) {
        Tokens.findOne({
            token: req.body.token
        }).then(tok => {
            if (tok) {
                let data = {
                    token: `Bearer ${tok.token}`
                }
                jsonParse.sendResult(res, 200, data, '登录成功')
            } else {
                jsonParse.sendResult(res, -103)
            }
        })
    },
    /**
     * Get 
     * api/loginOut
     * 登出接口
     *  */
    async loginOut(req, res) {
        const token = req.headers['Authorization'] || req.headers['authorization']
        await Tokens.findOneAndDelete({
            token: token
        }).then(out => {
            jsonParse.sendResult(res, 200, '', '退出成功')
        })
    },

    /**
     * Post 
     * api/register
     * 注册接口
     *  */
    async register(req, res) {
        Users.findOne({
            userName: req.body.userName,
        }).then(user => {
            if (user) {
                jsonParse.sendResult(res, 400, '', '用户名称已存在')
            } else {
                const avatar = gravatar.url(req.body.userName, {
                    s: '200',
                    r: 'pg',
                    d: 'mm'
                })
                const count = Users.count()
                const newUser = new Users({
                    nickName: req.body.nickName,
                    userName: req.body.userName,
                    avatar,
                    passWord: req.body.passWord || '123',
                    roleIds: req.body.roleIds,
                    stationId: req.body.stationId,
                    status: 1,
                    delFlag: false,
                    id: count
                })
                bcrypt.genSalt(10, function (err, salt) {
                    bcrypt.hash(newUser.passWord, salt, function (err, hash) {
                        if (err) throw err;
                        newUser.passWord = hash
                        newUser.save().then(user => {
                            jsonParse.sendResult(res, 200, '', '创建成功')
                            // if (user) {
                            //     let list = req.body.roleIds.map(e => {
                            //         return {
                            //             userName: req.body.userName,
                            //             roleId: e,
                            //         }
                            //     })
                            //     UserRelatRoles.insertMany(list).then(role => {
                            //         jsonParse.sendResult(res, 200, '', '创建成功')
                            //     })
                            // } else {
                            //     jsonParse.sendResult(res, -1001)

                            // }

                        }, err => {
                            res.json(err)
                        })
                    });
                })
            }
        })
    },

    // 更新用户信息
    async updateUser(req, res) {
        console.log(req.body)
        Users.findByIdAndUpdate({
            _id: new ObjectId(req.body._id)
        }, {
            $set: {
                ...req.body
            }
        }).then(user => {
            jsonParse.sendResult(res, 200, '', '创建成功')
        })
    },
    /**
     * Get 
     * api/getUserInfo
     * 获取用户信息
     *  */
    async getUserInfo(req, res) {
        const userName = await Header.getUser(req)
        Users.findOne({
            userName: userName
        }, {
            userName: 1,
            nickName: 1,
            roleIds: 1
        }).then(user => {
            if (user) {
                // 通过角色Id获取角色
                RoleLists.find({
                    id: {
                        $in: user['roleIds']
                    }
                }).then(roles => {
                    if (roles) {
                        // 通过角色ID 查询 角色菜单关联表 获取菜单Id
                        RoleRelatMenu.find({
                            roleId: {
                                $in: user['roleIds']
                            }
                        }).then(menuIds => {
                            if (menuIds) {
                                // 获取菜单Id ，去重
                                let ids = Array.from(new Set(menuIds.map(e => {
                                    return new ObjectId(e.menuId)
                                })))
                                MenusLists.find({
                                    _id: {
                                        $in: ids
                                    }
                                }).then(menus => {
                                    const list = JSON.parse(JSON.stringify(menus))
                                    list.forEach(el => {
                                        if (el.menuType == 1) {
                                            let children = list.filter(e => e.parentId == el._id)
                                            el.children = children
                                        }
                                    })
                                    let menuList = list.filter(e => e.parentId == -1)
                                    jsonParse.sendResult(res, 200, {
                                        menuList: menuList,
                                        roleList: roles,
                                        userName: user.userName,
                                        nickName: user.nickName
                                    })
                                })
                            } else {
                                jsonParse.sendResult(res, -203, '用户未绑定菜单')
                            }
                        })
                    } else {
                        jsonParse.sendResult(res, -203, '用户未绑定角色')
                    }
                })

            } else {
                jsonParse.sendResult(res, -2005)
            }
        })
    },

    async getUserInfoApp(req, res) {

    },

    /**
     * Post 
     * api/getUserList
     * 获取用户列表
     *  */
    async getUserList(req, res) {
        let total = await Users.count()
        let {
            pageSize,
            pageNum,
            userName
        } = req.body;
        let data = {}
        await Users.find(data, {
            passWord: 0
        }).skip(pageSize * (pageNum - 1)).limit(pageSize).then(async users => {
            const row = JSON.parse(JSON.stringify(users))
            row.forEach(e => {
                let params = {
                    roleId: {
                        $in: e.roleIds
                    }
                }
                Promise.all([
                    RoleLists.find({
                        id: {
                            $in: e.roleIds
                        }
                    }),
                    RoleRelatMenu.find(params, {
                        menuId: 1
                    }),
                    RoleRelatHandleAuth.find(params, {
                        authId: 1
                    }),
                    RoleRelatDataAuth.find(params, {
                        dataAuthId: 1
                    }),
                    CarStation.findById({
                        _id: new ObjectId(e.stationId)
                    }, {
                        stationName: 1
                    })
                ]).then(os => {
                    e.roles = os[0]
                    e.menus = os[1]
                    e.auths = os[2]
                    e.datas = os[3]
                    e.station = os[4]
                })
            })

            setTimeout(() => {
                jsonParse.sendResult(res, 200, {
                    total,
                    records: row
                }, '获取成功')
            }, 300)
        })
    },

    /**
     * Post 
     * api/getUserInfo
     * 更新用户信息
     *  */
    async updateUserInfo(req, res) {
        Users.findOneAndUpdate({
            userName: req.body.userName
        }, {
            $set: {
                ...req.body
            }
        }).then(user => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/getMenuLists
     * 获取用户菜单
     *  */
    async getMenuLists(req, res) {
        let data = {
            clientId: req.body.clientId
        }
        await MenusLists.find(data).then(async menu => {
            const list = JSON.parse(JSON.stringify(menu))
            list.forEach(el => {
                if (el.menuType == 1) {
                    let children = list.filter(e => e.parentId == el._id)
                    el.children = children
                }
            })
            let menuList = list.filter(e => e.parentId == -1)
            jsonParse.sendResult(res, 200, {
                menuList: menuList,
                permissions: []
            }, '获取成功')
        })
    },
    /**
     * Post 
     * api/saveMenu
     * 保存菜单
     *  */
    async saveMenu(req, res) {
        const newMenu = new MenusLists({
            ...req.body,
        })
        newMenu.save().then(menu => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/updateMenu
     * 更新菜单
     *  */
    async updateMenu(req, res) {
        MenusLists.findByIdAndUpdate({
            _id: new ObjectId(req.body.id)
        }, {
            $set: {
                ...req.body
            }
        }).then(menu => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/deleteMenu
     * 删除菜单
     *  */
    async deleteMenu(req, res) {
        MenusLists.findOneAndDelete({
            _id: new ObjectId(req.body.id)
        }).then(menu => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/getAuthLists
     * 获取对应菜单按钮权限
     *  */
    async getAuthLists(req, res) {
        let {
            clientId,
            menuId
        } = req.body
        AuthLists.find({
            clientId,
            menuId
        }).then(auth => {
            jsonParse.sendResult(res, 200, auth, '查询成功')
        })
    },

    /**
     * Post 
     * api/saveAuth
     * 保存菜单按钮权限
     *  */
    async saveAuth(req, res) {
        const newAuth = new AuthLists({
            ...req.body
        })
        newAuth.save().then(auth => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/getRoleLists
     * 获取角色列表
     *  */
    async getRoleLists(req, res) {
        let total = await RoleLists.count()
        let {
            pageSize,
            pageNum,
            roleName
        } = req.body;
        let data = {}
        if (roleName) {
            data.roleName = roleName
        }
        RoleLists.find(data).skip(pageSize * (pageNum - 1)).limit(pageSize).then(roles => {
            jsonParse.sendResult(res, 200, {
                total,
                records: roles
            }, '查询成功')
        })
    },

    /**
     * Post 
     * api/getRoleLists
     * 保存角色权限
     *  */
    async saveRoleAuth(req, res) {
        let {
            id,
            roleMenu,
            roleAuth,
            dataAuthIds,
            defaultAuthId
        } = req.body
        let dataAuth = dataAuthIds.map(e => {
            return {
                roleId: id,
                dataAuthId: e,
                defaultflag: e == defaultAuthId
            }
        })
        let menuList = roleMenu.map(e => {
            return {
                menuId: e,
                roleId: id
            }
        })
        let authList = roleAuth.map(e => {
            return {
                authId: e,
                roleId: id
            }
        })
        Promise.all([
            await RoleRelatDataAuth.deleteMany({
                roleId: id
            }),
            await RoleRelatMenu.deleteMany({
                roleId: id
            }),
            await RoleRelatHandleAuth.deleteMany({
                roleId: id
            }),
            await RoleRelatDataAuth.insertMany(dataAuth),
            await RoleRelatMenu.insertMany(menuList),
            await RoleRelatHandleAuth.insertMany(authList),
        ]).then(relat => {
            if (relat) {
                jsonParse.sendResult(res, 200)
            }
        })

    },

    /**
     * Post 
     * api/getRoleLists
     * 获取角色详情
     *  */
    getRoleDetailById(req, res) {
        RoleLists.aggregate([{
                $match: {
                    id: req.body.id
                }
            },
            {
                $lookup: {
                    from: 'role_relat_menus',
                    localField: 'id',
                    foreignField: 'roleId',
                    as: 'menuList'
                }
            },
            {
                $lookup: {
                    from: 'role_relat_handle_auths',
                    localField: 'id',
                    foreignField: 'roleId',
                    as: 'roleAuth'
                },
            },
            {
                $lookup: {
                    from: 'role_relat_data_auths',
                    localField: 'id',
                    foreignField: 'roleId',
                    as: 'dataAuthIds'
                }
            },

        ]).then(aggregate => {
            let data = aggregate[0]
            let defaultAuthId = ''
            let dataAuthIds = data.dataAuthIds.map(e => {
                if (e.defaultflag) {
                    defaultAuthId = e.dataAuthId
                }
                return e.dataAuthId
            })
            let obj = {
                _id: data._id,
                id: data.id,
                roleMenu: data.menuList.map(e => {
                    return e.menuId
                }),
                roleAuth: data.roleAuth.map(e => {
                    return e.authId
                }),
                dataAuthIds: dataAuthIds,
                defaultAuthId: defaultAuthId
            }
            jsonParse.sendResult(res, 200, obj, '查询成功')
        })
    },

    /**
     * Post 
     * api/saveRole
     * 保存角色
     *  */
    async saveRole(req, res) {
        let newRole = new RoleLists({
            ...req.body,
        })
        newRole.save().then(() => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/updateRole
     * 更新角色
     *  */
    async updateRole(req, res) {
        RoleLists.findOneAndUpdate({
            _id: req.body.id
        }, {
            $set: {
                ...req.body
            }
        }).then(role => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/deleteRole
     * 删除角色
     *  */
    async deleteRole(req, res) {
        RoleLists.findOneAndDelete({
            id: req.query.id
        }).then(role => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * Post 
     * api/saveRole
     * 获取权限树
     *  */
    async getAuthTree(req, res) {
        let app = await AppLists.find()
        let menu = await MenusLists.find()
        let auth = await AuthLists.find()
        const list = JSON.parse(JSON.stringify(menu))
        list.forEach(el => {
            let lists = auth.filter(o => el._id == o.menuId)
            if (list && list.length) {
                el.permissions = lists
                el.checkList = []
            }

        })
        list.forEach(el => {
            if (el.menuType == 1) {
                let children = list.filter(e => e.parentId == el._id)
                el.children = children
            }
        })
        const appList = JSON.parse(JSON.stringify(app))
        let menuList = appList.map(o => {
            let child = list.filter(e => e.parentId == -1 && e.clientId == o.value)
            o.children = child
            return o
        })
        jsonParse.sendResult(res, 200, {
            menuList
        }, '获取成功')
    },




    /**
     * Post 
     * api/saveRole
     * 更新权限树
     *  */
    // async saveRoleAuth(req,res) {
    //     RoleLists.findOneAndUpdate({
    //         _id: req.body.id
    //     }, {
    //         $set: {
    //             ...req.body
    //         }
    //     }).then(role => {
    //         jsonParse.sendResult(res, 200)
    //     })
    // }
}